import requests
from flask import Flask, abort
from flask import jsonify
from flask import render_template
from flask import request

app = Flask(__name__)
BASE_URL = 'http://glitfc.leanapp.cn'
# BASE_URL = 'HTTP://127.0.0.1:5000'


@app.route('/')
@app.route('/index')
def book_list_view():
    params = request.args.to_dict()
    response = requests.get(BASE_URL + "/book/book_list", params=params)
    render_data = response.json()
    if render_data.get("data"):
        for i in render_data['data']:
            update_time = i.get("updatedAt")
            i["updatedAt"] = update_time.get("iso")
        return render_template('novel.html', infos=render_data.get("data"))
    return render_template('novel.html', infos=[])


@app.route('/book_info/<bk_id>')
def book_info_view(bk_id):
    params = request.args.to_dict()
    # params['size'] = 100
    response = requests.get(BASE_URL + "/book/chapter_list/{}".format(bk_id), params=params)
    render_data = response.json()
    if render_data.get("data"):
        return render_template('book-info.html', infos=render_data.get("data"))
    return jsonify(render_data)


@app.route('/book_content/db/<zj_id>')
def book_content_db_view(zj_id):
    params = request.args.to_dict()
    response = requests.get(BASE_URL + "/book/content/db/{}".format(zj_id), params=params)
    render_data = response.json()
    if render_data.get("data"):
        return render_template('book-content.html', infos=render_data.get("data"))
    return jsonify(render_data)


@app.route('/book_content/url')
def book_content_url_view():
    params = request.args.to_dict()
    response = requests.get(BASE_URL + "/book/content/url", params=params)
    render_data = response.json()
    if render_data.get("data"):
        return render_template('book-content.html', infos=render_data.get("data"))
    return jsonify(render_data)


@app.route('/count/<class_>')
def get_count(class_='book'):
    """

    {"class":"book","count":19107,"where":{}}
    :param class_:
    :return:
    """
    params = request.args.to_dict()
    response = requests.get("{}/book/count/{}".format(BASE_URL, class_), params=params)
    render_data = response.json()
    return jsonify(render_data)


@app.route('/search/<word>')
def search(word):
    """

    {"class":"book","count":19107,"where":{}}
    :param class_:
    :return:
    """
    params = request.args.to_dict()
    response = requests.get("{}/book/search/{}".format(BASE_URL, word), params=params)
    render_data = response.json()
    return render_template('novel.html', infos=render_data.get("data"))


if __name__ == '__main__':
    app.run(port=5001)
